package de.tum.in.eist.poll.server;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.tum.in.eist.poll.shared.Feedback;
import de.tum.in.eist.poll.shared.Lecture;
import de.tum.in.eist.poll.shared.Lecturer;
import de.tum.in.eist.poll.shared.Student;
import de.tum.in.eist.poll.shared.User;
import de.tum.in.eist.poll.service.EistPollService;

@SuppressWarnings("serial")
public class EistPollServiceImpl extends RemoteServiceServlet implements
		EistPollService {

	public EistPollServiceImpl() {
	}

	@Override
	public User login(String name, String password)
			throws IllegalArgumentException {
		if (!CSVDatabase.isValidInput(name, password))
			throw new IllegalArgumentException("Wrong user name or password");
		return CSVDatabase.getUser(name);
	}

	@Override
	public List<Lecture> requestLectures(User user) {
		if (!CSVDatabase.isValidInput(user.getName(), user.getPassword()))
			return new LinkedList<Lecture>();

		List<Lecture> lectures = new LinkedList<Lecture>(
				CSVDatabase.getLectures());
		List<Lecture> lecturesBase = new LinkedList<Lecture>(lectures);

		user = CSVDatabase.getUser(user.getName());

		if ((user instanceof Lecturer)) {
			for (Lecture lecture : lecturesBase) {
				if (!lecture.getLecturer().getName().equals(user.getName())) {
					lectures.remove(lecture);
				}
			}
		}
		return lectures;
	}

	@Override
	public List<Feedback> requestFeedback(User user, Lecture lecture) {
		if (!CSVDatabase.isValidInput(user.getName(), user.getPassword()))
			return null;

		Lecture l = CSVDatabase.getLecture(lecture.getLectureID());
		if (l != null)
			return CSVDatabase.getFeedback(user, l);
		return null;
	}

	@Override
	public String submitFeedback(Feedback feedback) {
		if (!CSVDatabase.isValidInput(feedback.getStudent().getName(), feedback
				.getStudent().getPassword()))
			return "user not known";

		Lecture lecture = CSVDatabase.getLecture(feedback.getLecture()
				.getLectureID());

		if (lecture == null)
			return "Lecture does not exist";

		User user = CSVDatabase.getUser(feedback.getStudent().getName());
		if (!(user instanceof Student))
			return "Is not a student";

		Student student = (Student) user;

		if (feedback.getLecture().containsStudent(student))
			return "already submitted feedback";

		CSVDatabase.addFeedbackToLecture(lecture, feedback);
		return "Your submission was successful!";
	}

}
